package com.example.springbootvue.security;

import com.example.springbootvue.entity.User;
import com.example.springbootvue.service.UserService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.Collections;

/**
 * 自定义 UserDetailsService 实现
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class CustomUserDetailsService implements UserDetailsService {

    private final UserService userService;

    @Override
    public UserDetails loadUserByUsername(String usernameOrEmail) throws UsernameNotFoundException {
        log.info("尝试加载用户: {}", usernameOrEmail);

        // 允许使用用户名或邮箱登录
        User user = userService.findByUsernameOrEmail(usernameOrEmail);

        if (user == null) {
            log.error("未找到用户: {}", usernameOrEmail);
            throw new UsernameNotFoundException("未找到用户: " + usernameOrEmail);
        }

        log.info("成功加载用户: {}, 密码哈希长度: {}",
                user.getUsername(),
                user.getPassword() != null ? user.getPassword().length() : 0);

        // 打印密码哈希的前10个字符，用于调试
        if (user.getPassword() != null && user.getPassword().length() > 10) {
            log.info("密码哈希前缀: {}", user.getPassword().substring(0, 10));
        }

        return org.springframework.security.core.userdetails.User.builder()
                .username(user.getUsername())
                .password(user.getPassword())
                .authorities(Collections.singletonList(new SimpleGrantedAuthority("ROLE_USER")))
                .build();
    }
}